<template>
	<view class="register-container">
		<scroll-view class="form-container" scroll-y>
			<!-- 负责人信息 -->
			<view class="form-section">
				<view class="input-item">
					<text class="label">负责人：</text>
					<input class="input" type="text" placeholder="请输入负责人姓名" v-model="verification.director" />
				</view>
				<view class="input-item">
					<text class="label">用户名：</text>
					<input class="input" type="text" placeholder="请输入用户名" v-model="userinfo.username" />
				</view>
				<view class="input-item">
					<text class="label">密码：</text>
					<input class="input" type="password" placeholder="请输入密码" v-model="userinfo.password" />
				</view>
				<view class="input-item">
					<text class="label">身份证号码：</text>
					<input class="input" type="idcard" placeholder="请输入身份证号码" v-model="verification.idCard" />
				</view>
				<view class="input-item">
					<text class="label">手机号：</text>
					<input class="input" type="number" placeholder="请输入手机号" v-model="verification.mobile" />
				</view>
				<view class="input-item code-item">
					<text class="label">验证码：</text>
					<input class="input" type="number" placeholder="请输入验证码" v-model="userinfo.code" />
					<!-- 					<button class="code-btn" @click="getCode" :disabled="countdown > 0">
						{{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
					</button> -->
				</view>
				<image :src="codeimg" style="width: 300px; height: 100px;" @click="getcode" />
			</view>

			<!-- 店铺信息 -->
			<view class="form-section">
				<view class="input-item">
					<text class="label">店名：</text>
					<input class="input" type="text" placeholder="请输入店名" v-model="merchant.name" />
				</view>
				<view class="input-item">
					<text class="label">工商营业执照号码：</text>
					<input class="input" type="text" placeholder="请输入营业执照号码" v-model="verification.businessLicenseId" />
				</view>
				<view class="input-item">
					<text class="label">经营开始时间：</text>
					<picker mode="time" value="" start="00:00:00" end="23:59:59"
						@change="(e) => merchant.startTime = e.detail.value">
						<!-- 用按钮/文本显示选中值，模拟输入框外观 -->
						<view class="input time-picker">
							{{ merchant.startTime || '请选择时间' }}
						</view>
					</picker>
				</view>
				<view class="input-item">
					<text class="label">经营结束时间：</text>
					<picker mode="time" value="" start="00:00:00" end="23:59:59"
						@change="(e) => merchant.endTime = e.detail.value">
						<!-- 用按钮/文本显示选中值，模拟输入框外观 -->
						<view class="input time-picker">
							{{ merchant.endTime || '请选择时间' }}
						</view>
					</picker>
				</view>
				<view class="input-item">
					<text class="label">经营区域：</text>
					<input class="input" type="text" placeholder="请输入经营区域" v-model="merchant.operatingArea" />
				</view>
				<view class="input-item">
					<text class="label">地址：</text>
					<input class="input" type="text" placeholder="请输入详细地址" v-model="merchant.address" />
				</view>
				<view class="container">
					<!-- 地图容器 -->
					<view class="map-box">
						<view id="amapContainer" style="width: 100%; height: 600rpx;"></view>
					</view>
					<!-- 选点结果展示 -->
					<view class="result-box">
						<!-- 						<view class="result-item">
							<text class="label">选中地址：</text>
							<text class="value">{{ address }}</text>
						</view> -->
						<view class="result-item">
							<text class="label">经度：</text>
							<text class="value">{{ longitude }}</text>
						</view>
						<view class="result-item">
							<text class="label">纬度：</text>
							<text class="value">{{ latitude }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 商家简介 -->
			<view class="form-section">
				<text class="section-title">商家简介</text>
				<textarea class="textarea" placeholder="请准确介绍一下公司的情况" v-model="merchant.description"></textarea>
			</view>

			<!-- 营业执照上传 -->
			<view class="form-section">
				<text class="section-title">营业执照</text>
				<view class="upload-container">
					<view class="upload-item" @click="chooseImage('businessLicenseImg')">
						<template v-if="verification.businessLicenseImg">
							<image class="uploaded-img" :src="verification.businessLicenseImg" mode="aspectFill"></image>
							<view class="delete-icon" @click.stop="deleteImage('businessLicenseImg')">×</view>
						</template>
						<template v-else>
							<image class="upload-icon" src="/static/icon-plus.png"></image>
							<text class="upload-text">上传照片</text>
						</template>
					</view>
				</view>
			</view>

			<!-- 身份证照片 -->
			<view class="form-section">
				<text class="section-title">身份证正反面照片（必传）</text>
				<view class="upload-container">
					<view class="upload-item" @click="chooseImage('front')">
						<template v-if="verification.front">
							<image class="uploaded-img" :src="verification.front" mode="aspectFill"></image>
							<view class="delete-icon" @click.stop="deleteImage('front')">×</view>
						</template>
						<template v-else>
							<image class="upload-icon" src="/static/icon-plus.png"></image>
							<text class="upload-text">上传人像面</text>
						</template>
					</view>
					<view class="upload-item" @click="chooseImage('opposite')">
						<template v-if="verification.opposite">
							<image class="uploaded-img" :src="verification.opposite" mode="aspectFill"></image>
							<view class="delete-icon" @click.stop="deleteImage('vopposite')">×</view>
						</template>
						<template v-else>
							<image class="upload-icon" src="/static/icon-plus.png"></image>
							<text class="upload-text">上传国徽面</text>
						</template>
					</view>
				</view>
			</view>

			<!-- 门店照片 -->
			<view class="form-section">
				<text class="section-title">门店照片</text>
				<view class="upload-container">
					<view class="upload-item" @click="chooseImage('merchantimg.img')">
						<template v-if="merchantimg.img">
							<image class="uploaded-img" :src="merchantimg.img" mode="aspectFill"></image>
							<view class="delete-icon" @click.stop="deleteImage('merchantimg.img')">×</view>
						</template>
						<template v-else>
							<image class="upload-icon" src="/static/icon-plus.png"></image>
							<text class="upload-text">上传照片</text>
						</template>
					</view>
				</view>
			</view>
			<!-- 注册按钮 -->
			<button class="submit-btn" @click="submitForm" :loading="loading">注册</button>
		</scroll-view>
	</view>
</template>

<script>
	import {
		get,
		post
	} from '../../utils/request.js';

	export default {
		data() {
			return {
				// 地图实例
				map: null,
				// 选中的经纬度
				longitude: '', // 经度
				latitude: '', // 纬度
				// 选中的地址信息
				address: '未选择地址',
				loading: false,
				userinfo: {
					code: '',
					confirmPassword: '',
					password: '',
					username: '',
					uuid: ''
				},
				fileList1: [],
				merchantimg:{
					img: '',
					mId:''
				},
				verification: {
					director: '',
					idCard: '',
					mobile: '',
					front: '',
					opposite: '',
					businessLicenseId: '',
					businessLicenseImg:''
				},
				merchant: {
					name: '',
					licenseNo: '',
					address: '',
					description: '',
					operatingArea: '',
					longitude: '',
					latitude: '',
					startTime: '',
					endTime: ''
				},
				region: [],
				regionText: '',
				countdown: 0,
				timer: null,
				codeimg: '',
				captchaEnabled: true,
			};
		},
		onUnload() {
			if (this.timer) clearInterval(this.timer);
		},
		methods: {
			handleTimeChange() {
				// 自动获取选择的时间并打印（可根据需要修改逻辑）
				console.log('选中的经营开始时间:', this.merchant.startTime)
				// 如需格式化处理，可在这里添加
			},
			// 获取验证码图片
			async getcode() {
				const resp = await get('/dev-api/code', {});
				this.captchaEnabled = resp.captchaEnabled !== false;
				if (this.captchaEnabled) {
					this.codeimg = "data:image/gif;base64," + resp.img;
					this.userinfo.uuid = resp.uuid;
				}
			},

			// 获取短信验证码
			getCode() {
				if (!this.formData.phone) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}

				this.countdown = 60;
				this.timer = setInterval(() => {
					if (this.countdown <= 0) {
						clearInterval(this.timer);
						return;
					}
					this.countdown--;
				}, 1000);

				// 调用获取验证码接口
				post('/dev-api/sms/send', {
					phone: this.formData.phone,
					uuid: this.userinfo.uuid,
					code: this.userinfo.code
				}).then(res => {
					uni.showToast({
						title: '验证码已发送',
						icon: 'success'
					});
				});
			},

			// 删除图片
			deleteImage(type) {
				// 清除对应的数据（关键修复）
				if (type === 'merchantimg.shopphoto') {
					this.merchantimg.shopphoto = '';
				} else {
					this.verification[type] = '';
				}
			},

			// 地区选择
			onRegionChange(e) {
				this.region = e.detail.value;
				this.regionText = this.region.join(' ');
				this.formData.region = this.region;
			},

			chooseImage(type) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						const tempFile = res.tempFiles[0];
						const localPath = tempFile.path;
						// 根据类型保存到正确的对象中（关键修复）
						if (type === 'merchantimg.img') {
							this.merchantimg.img = localPath; // 门店照片存到 shopphoto
						} else {
							this.verification[type] = localPath; // 其他照片存到 verification
						}

						// 尝试上传到服务器
						try {
							const uploadRes = await this.uploadFile(tempFile.path);
							if (uploadRes && uploadRes.startsWith('http')) {
								// 延迟更新为网络路径
								setTimeout(() => {
									if (type === 'merchantimg.img') {
										this.merchantimg.img = uploadRes;
									} else {
										this.verification[type] = uploadRes;
									}
								}, 300);
							} else {
								throw new Error('网络路径无效，保留本地路径');
							}
						} catch (err) {
							uni.showToast({
								title: '图片上传失败',
								icon: 'none'
							});
						}
					}
				});
			},
			async uploadFile(filePath) {
				return new Promise((resolve, reject) => {
					const token = uni.getStorageSync('token') || '';
					uni.uploadFile({
						url: 'http://localhost/dev-api/file/upload',
						filePath: filePath,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + token,
						},
						formData: {},
						success: (res) => {
							if (res.statusCode === 200) {
								try {
									const response = JSON.parse(res.data);
									if (response.code === 200) {
										// 1. 适配后端返回的不同格式（根据实际返回调整）
										let imagePath = '';
										if (typeof response.data === 'string') {
											// 情况1：后端直接返回路径字符串（如 "/statics/xxx.jpg"）
											imagePath = response.data;
										} else if (response.data && response.data.url) {
											// 情况2：后端返回对象，路径在url字段（如 { url: "/statics/xxx.jpg" }）
											imagePath = response.data.url;
										} else {
											// 无法解析路径时直接报错
											reject(new Error('无法从后端响应中获取图片路径'));
											return;
										}

										// 2. 拼接完整URL（确保以http开头且格式正确）
										const baseUrl = 'http://127.0.0.1:9300';
										let fileUrl = '';
										if (imagePath.startsWith('http')) {
											// 若后端已返回完整URL，直接使用
											fileUrl = imagePath;
										} else {
											// 拼接baseUrl（注意处理斜杠，避免重复或缺失）
											fileUrl = baseUrl + (imagePath.startsWith('/') ? '' :
												'/') + imagePath;
										}
										resolve(fileUrl);
									} else {
										reject(new Error(`上传失败：${response.msg || '未知错误'}`));
									}
								} catch (e) {
									reject(new Error(`解析响应失败：${e.message}`));
								}
							} else {
								reject(new Error(`上传失败，状态码：${res.statusCode}`));
							}
						},
						fail: (err) => {
							reject(new Error(`请求失败：${err.errMsg}`));
						}
					});
				});
			},
			// uView上传组件处理
			async afterRead(event) {
				const lists = [].concat(event.file);
				const name = event.name;

				lists.forEach((item, index) => {
					this[`fileList${name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});

					this.uploadFile(item.url).then(res => {
						if (res) {
							this[`fileList${name}`][index].status = 'success';
							this[`fileList${name}`][index].url = res;
							this.formData.businessLicense = res; // 保存营业执照URL
						} else {
							this[`fileList${name}`][index].status = 'failed';
							this[`fileList${name}`][index].message = '上传失败';
						}
					});
				});
			},

			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},

			// 表单验证
			validateForm() {
				if (!this.userinfo.username) {
					uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					});
					return false;
				}
				if (!this.userinfo.password || this.userinfo.password.length < 6) {
					uni.showToast({
						title: '密码不能少于6位',
						icon: 'none'
					});
					return false;
				}
				if (!this.formData.name) {
					uni.showToast({
						title: '请输入负责人姓名',
						icon: 'none'
					});
					return false;
				}
				if (!/^\d{17}[\dXx]$/.test(this.formData.idCard)) {
					uni.showToast({
						title: '请输入正确的身份证号码',
						icon: 'none'
					});
					return false;
				}
				if (!this.formData.businessLicense) {
					uni.showToast({
						title: '请上传营业执照',
						icon: 'none'
					});
					return false;
				}
				if (!this.formData.idCardFront || !this.formData.idCardBack) {
					uni.showToast({
						title: '请上传身份证正反面照片',
						icon: 'none'
					});
					return false;
				}
				return true;
			},

			// 提交表单
			async submitForm() {
			    // 事务管理：记录已成功执行的操作，用于回滚
			    const transactionLog = [];
			    let isSuccess = false;
			
			    try {
			        // 1. 原有注册逻辑
			        this.userinfo.confirmPassword = this.userinfo.password
			        const res = await post('/dev-api/auth/register', this.userinfo);
			        transactionLog.push({ action: 'register', id: res.userId }); // 记录注册操作
			
			        // 2. 原有获取用户信息逻辑
			        const res1 = await get('/dev-api/system/user/profile/' + this.userinfo.username, {})
			        console.log(res1)
			        this.verification.sysuserId = res1.userId
			
			        // 3. 原有创建商户逻辑
			        console.log(this.verification)
			        const res2 = await post('/dev-api/system/merchant', this.merchant)
			        transactionLog.push({ action: 'merchant', id: res2.id }); // 记录商户创建
			
			        // 4. 原有商户名称检查逻辑
			        const res3 = await get('/dev-api/system/merchant/list/name/' + this.merchant.name, {})
			        console.log(res3)
			        if (res3.length > 1) {
			            uni.showToast({
			                title: '商户名称重复',
			                icon: 'none'
			            });
			            throw new Error('商户名称重复'); // 触发回滚
			        } else if (res3.length === 1) {
			            console.log(res3)
			            console.log(res3[0].id)
			            this.verification.mid = res3[0].id
			            this.merchantimg.mid = res3[0].id
			            console.log(this.verification)
			            // 5. 原有提交认证逻辑
			            const res4 = await post('/dev-api/system/verification', this.verification)
			            transactionLog.push({ action: 'verification', id: res4.id }); // 记录认证提交
			
			            // 6. 原有提交图片逻辑
			            const res5 = await post('/dev-api/system/imgs', this.merchantimg)
			            transactionLog.push({ action: 'imgs', id: res5.id }); // 记录图片提交
			        }
			        isSuccess = true;
			        uni.showToast({ title: '所有操作成功', icon: 'success' });
					uni.navigateTo({
						url:"/pages/login/login"
					})
			
			    } catch (error) {
			        console.error('操作失败，开始回滚:', error);
			        // 执行回滚（按相反顺序撤销操作）
			        for (let i = transactionLog.length - 1; i >= 0; i--) {
			            const { action, id } = transactionLog[i];
			            try {
			                switch (action) {
			                    case 'register':
			                        await post('/dev-api/auth/unregister', { userId: id }); // 注销用户
			                        break;
			                    case 'merchant':
			                        await delete('/dev-api/system/merchant/' + id); // 删除商户
			                        break;
			                    case 'verification':
			                        await delete('/dev-api/system/verification/' + id); // 删除认证
			                        break;
			                    case 'imgs':
			                        await delete('/dev-api/system/imgs/' + id); // 删除图片
			                        break;
			                }
			                console.log(`已回滚：${action}（ID: ${id}）`);
			            } catch (rollbackErr) {
			                console.error(`回滚${action}失败:`, rollbackErr);
			            }
			        }
			        uni.showToast({ title: '操作失败，已尝试回滚', icon: 'none' });
			    }
			
			    return isSuccess;
			},

			// 初始化高德地图
			initAmap() {
				// 1. 加载高德地图API（需替换为自己的Key）
				const AMapKey = 'eaa02545e0d409deaac1465aecf252aa'; // 替换为你的Key（在高德开放平台申请）
				// 动态引入高德地图JSAPI
				const script = document.createElement('script');
				script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMapKey}`;
				script.type = 'text/javascript';
				document.body.appendChild(script);

				// 2. 地图加载完成后初始化
				script.onload = () => {
					// 创建地图实例（绑定到id为amapContainer的DOM）
					this.map = new AMap.Map('amapContainer', {
						zoom: 14, // 初始缩放级别
						center: [116.397428, 39.90923], // 初始中心点（北京）
						resizeEnable: true // 允许地图自适应容器大小变化
					});

					// 3. 添加地图点击事件（选点）
					this.map.on('click', (e) => {
						// 获取点击位置的经纬度
						const {
							lng,
							lat
						} = e.lnglat;
						this.longitude = lng.toFixed(6); // 保留6位小数
						this.latitude = lat.toFixed(6);
						this.merchant.longitude = this.longitude
						this.merchant.latitude = this.latitude
						// 4. 调用逆地理编码，根据经纬度获取地址信息
						this.getAddressByLngLat(lng, lat);

						// 在地图上标记选点（添加Marker）
						this.addMarker(lng, lat);
					});
				};
			},

			// 根据经纬度获取地址信息（逆地理编码）
			getAddressByLngLat(lng, lat) {
				// 先判断 AMap 是否存在，避免未加载完成就调用
				if (typeof AMap === 'undefined') {
					uni.showToast({
						title: '地图 API 加载失败',
						icon: 'none'
					});
					return;
				}
				AMap.plugin('AMap.Geocoder', () => {
					const geocoder = new AMap.Geocoder({
						radius: 1000,
						extensions: 'all'
					});
				});
			},

			// 在地图上添加标记点（Marker）
			addMarker(lng, lat) {
				// 先清除已有的标记
				this.map.remove(this.map.getAllOverlays('marker'));

				// 添加新标记
				const marker = new AMap.Marker({
					position: [lng, lat], // 标记位置
					title: '选中位置',
					icon: new AMap.Icon({
						size: new AMap.Size(40, 40), // 图标大小
						image: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
						imageSize: new AMap.Size(40, 40)
					})
				});

				// 将标记添加到地图
				marker.setMap(this.map);
			},

			// 确认选择（可根据需求处理结果）
			onConfirm() {
				if (!this.longitude || !this.latitude) {
					uni.showToast({
						title: '请先选择地址',
						icon: 'none'
					});
					return;
				}

				// 1. 输出结果（实际项目中可用于表单提交等）
				console.log('选中结果：', {
					address: this.address,
					longitude: this.longitude,
					latitude: this.latitude
				});

				// 2. 弹窗提示
				uni.showModal({
					title: '选择成功',
					content: `地址：${this.address}\n经纬度：${this.longitude}, ${this.latitude}`,
					showCancel: false
				});
			}
		},
		onLoad() {
			this.getcode();
			this.initAmap();
		},
		onUnload() {
			if (this.map) {
				this.map.destroy(); // 销毁地图实例，释放资源
			}
		}
	};
</script>

<style scoped>
	/* 保持原有的样式不变 */
	.register-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.form-container {
		flex: 1;
		padding: 20rpx;
	}

	.form-section {
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-right: 20rpx;
		margin-left: 20rpx;
	}

	.section-title {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 20rpx;
		display: block;
	}

	.input-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		box-sizing: border-box;
		border-bottom: 1rpx solid #eee;
	}

	.input-item:last-child {
		border-bottom: none;
	}

	.label {
		width: 240rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #666;
	}

	.input {
		flex: 1;
		font-size: 30rpx;
		color: #333;
	}

	.code-item {
		position: relative;
	}

	.code-btn {
		position: absolute;
		right: 0;
		width: 200rpx;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 24rpx;
		color: #3399ff;
		background-color: #fff;
		border: 1rpx solid #3399ff;
		border-radius: 30rpx;
	}

	.picker {
		flex: 1;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
	}

	.textarea {
		width: 100%;
		height: 200rpx;
		font-size: 28rpx;
		color: #333;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		padding: 20rpx;
		box-sizing: border-box;
	}

	.upload-container {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
	}

	.upload-item {
		width: 200rpx;
		height: 200rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		border: 1rpx dashed #ccc;
		position: relative;
		overflow: hidden;
	}

	.upload-icon {
		width: 60rpx;
		height: 60rpx;
		margin-bottom: 10rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
	}

	.uploaded-img {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}

	.delete-icon {
		position: absolute;
		top: 5rpx;
		right: 5rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
	}

	.submit-btn {
		margin: 40rpx 20rpx;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 32rpx;
		color: #fff;
		background-color: #3399ff;
		border-radius: 45rpx;
	}

	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 300rpx;
	}

	.map-box {
		margin-bottom: 30rpx;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.result-box {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
	}

	.result-item {
		display: flex;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.result-item:last-child {
		border-bottom: none;
	}

	.label {
		width: 160rpx;
		font-size: 28rpx;
		color: #666;
	}

	.value {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		word-break: break-all;
	}

	.confirm-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #3399ff;
		color: #fff;
		font-size: 32rpx;
		border-radius: 45rpx;
	}
</style>